package com.gzsxy.exception;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author xiaolong
 * @version 1.0
 * @description: OAuth自定义异常序列化
 * @date 2021/11/8 16:00
 */
public class CustomOAuthExceptionSerializer extends StdSerializer<CustomOAuthException> {


    private static final long serialVersionUID = 4260434962553681636L;

    public CustomOAuthExceptionSerializer() {
        super(CustomOAuthException.class);
    }

    @Override
    public void serialize(CustomOAuthException exception, JsonGenerator gen, SerializerProvider provider) throws IOException {

        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        gen.writeStartObject();
        gen.writeNumberField("code",exception.getHttpErrorCode());
        gen.writeStringField("msg",exception.getMessage());
        gen.writeStringField("path",req.getServletPath());
        gen.writeStringField("timestamp",String.valueOf(System.currentTimeMillis()));

        //处理附加信息
        if (exception.getAdditionalInformation() != null){
            for (Map.Entry<String,String> entry: exception.getAdditionalInformation().entrySet()){
                gen.writeStringField(entry.getKey(),entry.getValue());
            }
        }
        gen.writeEndObject();
    }
}
